/* eslint-disable react/jsx-closing-tag-location */
import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import { Button, Dialog, Form } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid, TitleGrid, refundModel, column, ENUMS } from '../stores/definitions';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';
import AttachmentPanel from './AttachmentPanel';
import TauTable from '@/components/TauTable';
import { uniqueId } from 'lodash';

const FromItem = Form.Item;

const subModal = refundModel.ticketRefundInfos;

const tableId = uniqueId('tauTable-');

function BusOrderRefund({ refund, modal, onSubmit, onCancel, onReject, isView, refundId }) {
  const { refundStore: store } = useStore();
  const [orderDetails, setOrderDetails] = useState([]);
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [orderRefund] = useState(() => observable({}));
  // 是否第一页
  const [type, setType] = useState();

  // 是否查看
  const view = isView[0] === 'view';

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      if (JSON.stringify(refund) !== '{}') {
        const data = await store.getIdRefund(refundId || refund.id);
        const refundInfo = await store.getRefund(data.refundId);
        const assembleData = {
          ...data,
          refund: refundInfo,
        };
        // 是否第一页
        const isInit = data.type === '0';
        setType(isInit);
        const detail = data.ticketRefundInfos;
        isInit && setOrderDetails([...detail]);
        editCtx.origin = _.cloneDeep(assembleData);
        _.assign(orderRefund, assembleData);
      }
    })();
  }, []);

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(orderRefund, name, value);
    editCtx.changed[name] = value === _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign, no-param-reassign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleSubmit = () => {
    Dialog.confirm({
      content: t`是否确认退款`,
      onOk: () => onSubmit?.(orderRefund),
    });
  };

  // 驳回
  const handleRefuse = () => {
    Dialog.confirm({
      content: t`是否驳回本次退款申请?`,
      onOk: () => onReject?.(orderRefund),
    });
  };

  return (
    <Form
      inline
      // isPreview={!view}
      value={orderRefund}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <TitleGrid title={t`退款信息`} />
      <FieldsGrid
        formData={orderRefund}
        mode={modal[0]}
        columns={4}
        fields={ENUMS.BUS_REFUND_TYPE[orderRefund?.type]}
      />

      {type && <TitleGrid title={t`车票信息`} />}
      {type && <div className="content">
        <TauTable
          instanceId={tableId}
          tableLayout="fixed"
          hidePagination
          dataSource={orderDetails}
          rowKey="id" // 设置每行的唯一标识
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('ticketCode', { width: 180 }, subModal),
            column('originalPrice', { width: 88 }, subModal),
            column('operatingState', { width: 180 }, subModal),
            column('state', { width: 88 }, subModal),
            column('operatorRefundTime', { width: 180 }, subModal),
            column('refundPrice', { width: 88 }, subModal),
            column('serviceCharge', { width: 88 }, subModal),
          ]}
        />
      </div>}

      <AttachmentPanel refund={orderRefund} mode={modal[0]} />

      <DrawerFooter>
        <FromItem>
          {!view && <Form.Submit validate style={{ marginRight: 10 }} type="primary" onClick={handleRefuse}>{t`驳回申请`}</Form.Submit>}
          {!view && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`确认退款`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
}

export default observer(BusOrderRefund);

